//
//  CharactersWindowController.m
//  EVE Mac Suite
//
//  Created by Vadim Lozko on 2/5/09.
//  Copyright 2009 __Vadim__. All rights reserved.
//

#import "EMSCharactersWindowController.h"
#import "EMSGeneralUtils.h"
#import "EVEAPIDownloader.h"
#import "EVEAPIDownloaderRequest.h"

@interface EMSCharactersWindowController (privateMethods)

-(id)initWithDelegate:(NSObject*)aDelegate;

@end


@implementation EMSCharactersWindowController

@synthesize delegate;
@synthesize progressText;
@synthesize characters;

+(EMSCharactersWindowController*)controller
{
	static EMSCharactersWindowController* controller;
	@synchronized(controller)
	{
		if(!controller)
		{
			controller = [[EMSCharactersWindowController alloc] initWithDelegate:self];
		} else {
			[[controller window] makeKeyAndOrderFront:nil];

		}
	}
	return controller;
}

-(void)windowDidLoad
{
	[userIDField setStringValue:@""];
	[apiKeyField setStringValue:@""];
	self.progressText = @"";
	[progressIndicator setHidden:NO];
}


-(void)dealloc
{
	if(userIDString)
		[userIDString release];
	if(apiKeyField)
		[apiKeyString release];
	[characters release];
	[progressText release];
	[super dealloc];
}

-(IBAction)searchForCharacters:(id)sender
{
	userIDString = [[userIDField stringValue] retain];
	apiKeyString = [[apiKeyField stringValue] retain];
	NSDictionary *requestDict = 
	[NSDictionary dictionaryWithObjectsAndKeys:userIDString, CHAR_INFO_DICT_USERID, apiKeyString, CHAR_INFO_DICT_APIKEY, nil];
	[[EVEAPIDownloader sharedDownloader] setDelegate:self];
	[[EVEAPIDownloader sharedDownloader] performAPIDownloadRequest:[EVEAPIDownloaderRequest requestWithType:@"Characters" 
																									   info:requestDict
																									handler:self]];
	self.progressText = @"Downloading...";
	[progressIndicator setHidden:NO];
	[progressIndicator startAnimation:nil];
}

-(void)downloadRequestDidFailWithError:(NSError*)error
{
	self.progressText = @"Error downloading from EVE API server. Please check your connection.";
	[progressIndicator stopAnimation:nil];
}

-(void)downloadRequestDidFinishForXMLDoc:(NSXMLDocument*)document
{
	self.progressText = @"";
	[progressIndicator stopAnimation:nil];
	[progressIndicator setHidden:YES];
	NSError* error = nil;
	NSArray* charXMLNodes = [document nodesForXPath:@"/eveapi/result/rowset/row" error:&error];
	[self willChangeValueForKey:@"characters"];
	[characters removeAllObjects];
	for(NSXMLElement *element in charXMLNodes)
	{
		NSMutableDictionary* charInfoDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
											 [[element attributeForName:@"name"] stringValue], CHAR_INFO_DICT_NAME,
											 [[element attributeForName:@"characterID"] stringValue] , CHAR_INFO_DICT_CHARID, 
											 [[element attributeForName:@"corporationName"] stringValue], CHAR_INFO_DICT_CORP, 
											 [[element attributeForName:@"corporationID"] stringValue], CHAR_INFO_DICT_CORPID,
											 userIDString, CHAR_INFO_DICT_USERID,
											 apiKeyString,  CHAR_INFO_DICT_APIKEY, 
											 [NSNumber numberWithBool:YES], @"isChecked",nil];
		[characters addObject:charInfoDict];
	}
	[self didChangeValueForKey:@"characters"];
	[userIDString release];
	userIDString = nil;
	[apiKeyString release];
	apiKeyString = nil;
	[selectButton highlight:YES];
	[selectButton becomeFirstResponder];
}

-(IBAction)selectCharacter:(id)sender
{
	if(self.characters && [self.characters count] > 0)
	{
		for(NSMutableDictionary* characterInfo in self.characters)
		{
			if([[characterInfo objectForKey:@"isChecked"] boolValue])
			{
				[characterInfo removeObjectForKey:@"isChecked"];
				[delegate createNewCharacterFromInfo:characterInfo];
			}
		}
		[self close];
		self.characters = [NSMutableArray array];
	}
	/*
	int selectedChar = [charactersTableView selectedRow];
	if(selectedChar != -1)
	{
		if([delegate respondsToSelector:@selector(createNewCharacterFromInfo:)])
		{
			[delegate createNewCharacterFromInfo:[[self characters] objectAtIndex:selectedChar]];
			[self close];
		}
	}*/
}

-(IBAction)cancel:(id)sender
{
	if([delegate respondsToSelector:@selector(addNewCharacterWindowDidCancel)])
	{
		[delegate addNewCharacterWindowDidCancel];
		[self close];
	}
}


@end

@implementation EMSCharactersWindowController (privateMethods)

-(id)initWithDelegate:(NSObject*)aDelegate
{
	self = [super initWithWindowNibName:@"CharacterSelector"];
	{
		characters = [[NSMutableArray alloc] init];
		delegate = aDelegate;
		progressText = [[NSMutableString alloc] init];
		[self loadWindow];
		[[self window] makeKeyWindow];
	}
	return self;
}

@end
